import 'dart:async';
import 'dart:io';

import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:love_newf/app/com/manage/location_manage/location_info.dart';
import 'package:love_newf/app/com/manage/location_manage/location_listener.dart';

class LocationManage {
  factory LocationManage() => _getInstance();

  static LocationManage get instance => _getInstance();
  static LocationManage? _instance;

  LocationManage._internal();

  static LocationManage _getInstance() {
    _instance ??= LocationManage._internal();
    return _instance!;
  }

  ///监听队列
  final List<LocationListener> _locationListens = [];

  ///当前获取定位 ，
  LocationInfo? currLocInfo;

  ///添加监听到队列
  addLocationListener(LocationListener listener) {
    if (!_locationListens.contains(listener)) _locationListens.add(listener);
  }

  ///移除监听
  removeLocationListener(LocationListener listener) {
    _locationListens.remove(listener);
  }

  ///开启定位
  startLocation() {}

  ///关闭定位
  closeLocation() {}

  ///得到一次定位
  Future<LocationInfo?> determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // return Future.error('Location services are disabled.');
      return null;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        //位置权限被拒绝
        // return Future.error('Location permissions are denied');
        return null;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // return Future.error(
      //     'Location permissions are permanently denied, we cannot request permissions.');
      return null;
    }

    Position? position = await getPosition();
    currLocInfo ??= LocationInfo();
    if (position == null) return currLocInfo;
    currLocInfo!.latitude = position.latitude;
    currLocInfo!.longitude = position.longitude;
    currLocInfo!.timestamp = position.timestamp;
    List<Placemark> placemarks = [];
    try {
      placemarks = await placemarkFromCoordinates(
          currLocInfo!.latitude, currLocInfo!.longitude);
    } catch (e) {}
    if (placemarks.isNotEmpty) {
      Placemark placemark =  placemarks[0];
      currLocInfo?.address = placemark.name!;
      currLocInfo?.country = placemark.country!;
      currLocInfo?.countryCode = placemark.isoCountryCode!;
      currLocInfo?.province = placemark.administrativeArea!;
      currLocInfo?.city = StringUtils.defaultValue(placemark.locality!, placemark.administrativeArea!);
      currLocInfo?.area = placemark.subLocality!;
      currLocInfo?.street = placemark.thoroughfare!;
      if(StringUtils.isEmpty(currLocInfo?.street)){
        currLocInfo?.street = placemark.name!;
      }
    }
    return currLocInfo;
  }

  Future<Position?> getPosition() {
    var streamController = StreamController<Position?>();

    Geolocator.getCurrentPosition(forceAndroidLocationManager: true)
        .then((Position position) {
      streamController.add(position);
      streamController.close();
    });
    //延时3秒
    Future.delayed(const Duration(seconds: 3), () async {
      if (!streamController.isClosed) {
        //3 秒后没有关闭 去那上一次的定位
        Position? position = await Geolocator.getLastKnownPosition(
            forceAndroidLocationManager: true);
        streamController.add(position);
        streamController.close();
      }
    });
    return streamController.stream.last;
  }

  getPositon1(StreamController streamController, Position? position1) async {
    Position? position = position1;
    position ??=
        await Geolocator.getCurrentPosition(forceAndroidLocationManager: true);
    streamController.add(position);
    streamController.close();
  }

  sleepPosition(StreamController streamController) async {
    Position? position = await Geolocator.getLastKnownPosition(
        forceAndroidLocationManager: true);
    streamController.add(position);
    streamController.close();
  }
}
